#include "pch.h"
#include "CHook.h"

CHook* pHook = NULL;

char g_data[] = {
	0x60,							// pushad
	0x9C,							// pushfd
	0x54,							// push esp
	0xE8, 0xCC, 0xCC, 0xCC, 0xCC,	// call fn
	0x9D,							//	popfd
	0x61							//	popad
};

void _stdcall DisHook(HOOKREFS) {
	LPVOID _eip = (LPVOID)(_EIP - 0x5);
	CHookPoint* p = pHook->m_HPoint.FindPoint(_eip);
	if (p) {
		if (p->m_HookBack(val)) {
			_EIP = (unsigned)(p->m_pCodeFix);
		}
	}
}



CHook::CHook()
{
	if (pHook) return;
	pHook = this;
	m_HPointLast = &m_HPoint;
	DWORD dwOld;
	VirtualProtect(g_data, sizeof(g_data), PAGE_EXECUTE_READWRITE, &dwOld);
	unsigned* pnDis = (unsigned*)(g_data + 0x4);
	unsigned nDis = GetJmpDis((unsigned)DisHook, (unsigned)(g_data + 0x3));
	pnDis[0] = nDis;
}

void CHook::SetHook(unsigned nAddr, short len, HOOKBACK HookBack, unsigned nAddrRet)
{
	DWORD dwOld;
	VirtualProtect((LPVOID)nAddr, len, PAGE_EXECUTE_READWRITE, &dwOld);
	m_HPointLast = m_HPointLast->AddPoint((LPVOID)nAddr, HookBack, len, nAddrRet);
	char* code = (char*)nAddr;
	code[0] = 0xE8;
	unsigned* pnDis = (unsigned*)(nAddr + 0x1);
	pnDis[0] = GetJmpDis((unsigned)g_data, nAddr);

	VirtualProtect((LPVOID)nAddr, len, dwOld, NULL);

	CString wTxt;
	wTxt.Format(L"%x", m_HPointLast->m_pCodeFix);
	AfxMessageBox(wTxt);
}
